package com.muki.spider;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.muki.spider.exception.SpiderNotWorkingException;
import com.muki.spider.moudle.MoudleSerial;

public class MukiSpiderManager implements SpiderManager {

	//派送名单
	//发送到注册中心的爬虫被管理者记录在名单中
	//在注册中心被回收的管理者会在记录名单递减
	//通过名单的计数适配各工作的调度
	private final Logger log = Logger.getLogger(MukiSpiderManager.class);
	private Map<String,Integer> panel = new HashMap<>();
	
	//正则规则
	private String regx = null;

	//设置主题
	private String topic = null;
	
	//销毁爬虫回收站
	//private List<String> releaseRecord = new ArrayList<>();
	private MoudleController moudle = MoudleController.getInstance();

	private SpiderFactory factory;
	
	private final String manager_name="muki_";
	private int number=1;

	public MukiSpiderManager(SpiderFactory factory) {
		this.factory = factory;
	}

	public MukiSpiderManager() {
		this.factory = MukiSpiderFactory.getInstance();
	}
	
	public void setRegx(String regx) {
		this.regx = regx;
	}
	
	public void setTopic(String topic) {
		this.topic = topic;
	}

	/**
	 * 统计计算各名单中的爬虫数量
	 */
	@Override public int total() {
		int total = 0;
		for(String key:panel.keySet()) {
			total += panel.getOrDefault(key,0);
		}
		return total;
	}

	/**
	 * 发送一个爬虫到指定的主题上去
	 */
	@Override public void sendSpiderToTopic(SpiderRegisteration registeration) {
		//从工厂创造一个Spider
		Spider spider = factory.createSpider();
		//将该Spider与topic绑定
		if(topic==null)
			throw new SpiderNotWorkingException("the manager has no topic!");
		log.info("接收："+topic+" "+regx);
		spider.bind(topic);
		spider.setName(topic+"_"+manager_name+(number++));
		
		if(regx!=null)
			spider.setRegx(regx);
		moudle.runSpiderToMoudle(MoudleSerial.SPIDER_STATICS, spider);
		registeration.register(spider);
		//从记事本中获取对应topic的爬虫调度情况，并记录
		Integer num = panel.getOrDefault(topic, 0);
		panel.put(topic, ++num);
	}

	@Override public void release(Spider spider) {
		String topic = spider.getTopic();
		Integer num = panel.getOrDefault(topic, 0);
		if(num>0)
			panel.put(topic, num--);
		moudle.runSpiderToMoudle(MoudleSerial.SPIDER_CYCLE, spider);
	}

	@Override
	public int getNum(String topic) {
		int num = panel.getOrDefault(topic, 0);
		return num;
	}

}
